/*
 * Copyright 2013 Tomas.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.heathtow.web.pages;

import cz.muni.fi.heathrowapi.HeathrowRoles;
import cz.muni.fi.heathrowapi.UserService;
import cz.muni.fi.heathrowapi.dto.UserDTO;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import org.apache.wicket.Component;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.AbstractItem;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;

/**
 *
 * @author Tomas
 */
@AuthorizeInstantiation(HeathrowRoles.ADMIN)
public class UsersView extends MainPage {

        
        @SpringBean(name = "userService")
        private static UserService service;
        
    public UsersView(PageParameters parameters) {
        super(parameters);

        showAll();

        final RegistrationForm regForm = new RegistrationForm("regForm");
        add(regForm);
    }
    public UsersView(PageParameters parameters, UserDTO user) {
        super(parameters);

        showAll();

        final RegistrationForm regForm = new RegistrationForm("regForm",user);
        add(regForm);
    }

    private static class RegistrationForm extends Form<Void> {

        private static final long serialVersionUID = -682685350753597783L;
        private UserDTO user = new UserDTO();
        private FormComponent<String> password;
        private CheckBox admin;
        private TextField<String> userName;
        
        public RegistrationForm(String id) {
            super(id);
            setModel(new CompoundPropertyModel(this));
            userName = new RequiredTextField("userName", new PropertyModel<String>(user, "username"));
            userName.setLabel(new ResourceModel("username.label"));
            password = new PasswordTextField("password", Model.of(""));
            password.setLabel(new ResourceModel("password.label"));
            TextField<String> cpassword = new PasswordTextField("cpassword", Model.of(""));
            cpassword.setLabel(new ResourceModel("controlpassword.label"));
            admin = new CheckBox("admin", Model.of(Boolean.FALSE));
            admin.setLabel(new ResourceModel("admin.label"));
            
            add(userName);
            add(password);
            add(cpassword);
            add(new EqualPasswordInputValidator(password, cpassword));
            add(admin);
            
            final FeedbackPanel feedback = new FeedbackPanel("feedback");
            feedback.setOutputMarkupId(true);
            add(feedback);
        }
        
        public RegistrationForm(String id, UserDTO user) {
            super(id);
            this.user = user;
            setModel(new CompoundPropertyModel(this));
            userName = new RequiredTextField("userName", new PropertyModel<String>(user, "username"));
            userName.setLabel(new ResourceModel("username.label"));
            password = new PasswordTextField("password", Model.of(""));
            password.setLabel(new ResourceModel("password.label"));
            password.setRequired(false);
            FormComponent<String> cpassword = new PasswordTextField("cpassword", Model.of(""));
            cpassword.setLabel(new ResourceModel("controlpassword.label"));
            cpassword.setRequired(false);
            if(user.getRoles().contains(HeathrowRoles.ADMIN)) 
                admin = new CheckBox("admin", Model.of(Boolean.TRUE));
            else
                admin = new CheckBox("admin", Model.of(Boolean.FALSE));
            admin.setLabel(new ResourceModel("admin.label"));
            
            add(userName);
            add(password);
            add(cpassword);
            add(new EqualPasswordInputValidator(password, cpassword));
            add(admin);
            
            final FeedbackPanel feedback = new FeedbackPanel("feedback");
            feedback.setOutputMarkupId(true);
            add(feedback);
        }

        @Override
        protected void onSubmit() {
            if(user.getId()==null){
                Set<String> role = new HashSet<String>();
                if(admin.getConvertedInput()){
                        role.add(HeathrowRoles.ADMIN);
                }
                role.add(HeathrowRoles.USER);
                user.setRoles(role);
                service.create(user);
                service.updatePassword(user,password.getValue());
                setResponsePage(new UsersView(new PageParameters()));
            }else{
                Set<String> role = new HashSet<String>();
                if(admin.getConvertedInput()){
                        role.add(HeathrowRoles.ADMIN);
                }
                role.add(HeathrowRoles.USER);
                user.setRoles(role);
                service.update(user);
                //pokud se heslo nerovna NULL tak updatuj i heslo
                if(password.getValue()!=null){
                    service.updatePassword(user,password.getValue());
                }
                setResponsePage(new UsersView(new PageParameters()));
            }
        }
        private static final Logger LOG = Logger.getLogger(RegistrationForm.class.getName());
    }
    
    private void showAll() {
        

        Component header = new AbstractItem("header");
        add(header);
        
        final RepeatingView repeatingView = new RepeatingView("repeating");
        add(repeatingView);

        
        
            for (final UserDTO user : service.findAll()) {
                AbstractItem item = new AbstractItem(repeatingView.newChildId());

                item.add(new Label("contactID", String.valueOf(user.getId())));
                item.add(new Label("nickName", user.getUsername()));
                item.add(new Label("roles", user.getRoles().toString()));
                Link edit = new Link("pensLink") {
                    @Override
                    public void onClick() {
                        setResponsePage(new UsersView(new PageParameters(),user));
                    }
                };
                item.add(edit);
                
                Link delete = new Link("crossLink") {
                    @Override
                    public void onClick() {
                        service.remove(user);
                        setResponsePage(new UsersView(new PageParameters()));
                    }
                };
                item.add(delete);
                

                repeatingView.add(item);
            }
        
    }
}
